package priv.mill.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;



public class JdbcUtil {

	private static final Logger logger = Logger.getLogger(JdbcUtil.class);
	
	public static interface JdbcVisitor{
		Object handlerResult(ResultSet resultSet);
	}
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
//		Integer excute = excute("update mm_books set b_price = ? where b_id = ?",125.6,6);
//		Integer excute = excute("delete from mm_books where b_id = ?",7); 
//		System.out.println(excute);
	}

	public static Integer excute(String sql, Object...args) throws ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver"); 
		Connection conn = null; 
		PreparedStatement pre = null; 
		try {
			conn = DriverManager.getConnection(Messages.getString("JdbcUtil.url"),
			           Messages.getString("JdbcUtil.user"), 
			                  Messages.getString("JdbcUtil.mima")); 
			pre = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				pre.setObject(i+1, args[i]);
			}
			int executeUpdate = pre.executeUpdate();
			return executeUpdate;
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (pre!=null)
			try {
				pre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (conn!=null)
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}


	public static Object queryAll(String sql,JdbcVisitor v, Object... args) throws ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver"); //$NON-NLS-1$
		Connection conn = null; //$NON-NLS-1$ //$NON-NLS-2$
		PreparedStatement pre = null; // $NON-NLS-1$
		ResultSet resultSet = null;
		try {
			conn = DriverManager.getConnection(Messages.getString("JdbcUtil.url"),
					           Messages.getString("JdbcUtil.user"), 
					                  Messages.getString("JdbcUtil.mima")); 
			pre = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				pre.setObject(i+1, args[i]);
			}
			resultSet = pre.executeQuery();
			List objs = new ArrayList();
			while (resultSet.next()) {
				Object handlerResult = v.handlerResult(resultSet);
				if (handlerResult!=null)
					objs.add(handlerResult);
			}
			return objs;
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (resultSet!=null)
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (pre!=null)
			try {
				pre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			if (conn!=null)
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
}